package easy;

/**
 * @Description : 将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
 * @Author : machong
 * @Date : 2022/3/29 1:53
 * @Version : 1.0
 **/
public class leetCode21_mergeTwoLists {
    public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
        /**
         * 方法一：非递归方法
         */
        ListNode result = new ListNode();
        ListNode pointer = result;
        while (list1 != null && list2 !=null){
            if (list1.val <= list2.val ){
                pointer.next = list1;
                list1 = list1.next;
            }else {
                pointer.next = list2;
                list2 = list2.next;
            }
            pointer = pointer.next;
        }
        if (list1==null || list2==null){
            pointer.next = list1 == null ? list2 : list1;
        }
        return result.next;
        /**
         * 方法二：递归法
         */
//        ListNode result = new ListNode();
//        if (list1 == null || list2 == null){
//            result = list1 == null ? list2 : list1;
//        }else if (list1.val <= list2.val){
//            result.val = list1.val;
//            result.next = mergeTwoLists(list1.next,list2);
//        }else {
//            result.val = list2.val;
//            result.next = mergeTwoLists(list1,list2.next);
//        }
//        return result;
    }

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode() {}
     *     ListNode(int val) { this.val = val; }
     *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
     * }
     */
    public class ListNode {
        int val;
        ListNode next;
        ListNode() {}
        ListNode(int val) { this.val = val; }
        ListNode(int val, ListNode next) { this.val = val; this.next = next; }
    }
}
